package yxk.task.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yxk.utils.BosUtil;
import yxk.utils.DateUtil;

import java.text.SimpleDateFormat;
import java.util.*;

import static kd.bos.servicehelper.operation.SaveServiceHelper.*;

/**
* @author lijiawang
* @Date 2023/5/31 11:11
* @Description:出差申请单
*/
    public class WtamBusitripselfbillServiceApi {
    private static Log logger = LogFactory.getLog(WtamBusitripselfbillServiceApi.class);
    private static WtamBusitripselfbillServiceApi INS = new WtamBusitripselfbillServiceApi();
    private RequesUtil requesUtil=new RequesUtil();
    public static WtamBusitripselfbillServiceApi getInstance() {
        return INS;
    }

    public BusitripseServiceMethod instance = BusitripseServiceMethod.getInstance();

    /**
     * 获取汇联易的出差申请申请单，获取时间前两个月到往后一年
     * @return
     */
    public String getHLYBusitripself(){
        List<Map<String,String>> list=new ArrayList<>();
        List<JSONArray> request = requesUtil.getHUYClockDataRequest();
        logger.info("WtamBusitripselfbillServiceApi.getHLYBusitripself.request:{}",request);
        for (JSONArray jsonArray : request) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject dataJSON=jsonArray.getJSONObject(i);
                //申请单的ID
                String applicationOID = dataJSON.getString("applicationOID");
                //状态
                String status = dataJSON.get("status").toString();
                //差旅申请单信息
                JSONObject travelApplication = dataJSON.getJSONObject("travelApplication");
                String startDate = travelApplication.getString("startDate");//开始时间
                String endDate = travelApplication.getString("endDate");//结束时间
                //创建人
                JSONObject createdUser = dataJSON.getJSONObject("createdUser");
                String employeeID = createdUser.getString("employeeID");
                String title="";
                try {
                    title = dataJSON.getString("title");
                }catch (Exception e){
                    logger.info("WtamBusitripselfbillServiceApi");
                }
                //人员信息
                JSONArray array = dataJSON.getJSONArray("simpleApplicationParticipants");
                for (int j = 0; j < array.size(); j++) {
                    Map<String,String> map=new HashMap<>();
                    JSONObject row = (JSONObject)array.get(j);
                    String userNumber = row.getString("employeeID");
                    map.put("userNumber",userNumber);
                    map.put("createuser",employeeID);
                    map.put("startTime",startDate);
                    map.put("endTime",endDate);
                    map.put("applicationOID",applicationOID+userNumber);
                    map.put("status",status);
                    map.put("title",title);
                    list.add(map);
                }
            }
        }
        String evectionBill = getEvectionBill(list);
        return evectionBill;
    }

    /**
     * 出差申请单同步
     * @param param  接口获取的出差申请单
     * @return
     */
    public String  getEvectionBill(List<Map<String,String>> param){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DynamicObject tripType = BusinessDataServiceHelper.loadSingleFromCache("wtbd_traveltype", "id", new QFilter("number", QCP.equals, "1010_S").toArray());
        for (int i = 0; i < param.size(); i++) {
            try {
                Map<String, String> paramMap = param.get(i);
                String userNumber = paramMap.get("userNumber");
                logger.info("WtamBusitripselfbillServiceApi=======userNumber:{},paramMap{}",userNumber, paramMap);
                String applicationOID = paramMap.get("applicationOID");
                QFilter attQF = new QFilter("attperson.number", QCP.equals, userNumber)
                        .and("iscurrentversion", QCP.equals, '1');
                DynamicObject wtpAttfilebase = BusinessDataServiceHelper.loadSingle("wtp_attfilebase", "id,org,attperson.id,attperson,attperson.number", attQF.toArray());
                if(wtpAttfilebase == null){
                    logger.info("人员未匹配到考勤档案,工号{}",userNumber);
                    continue;
                }
                String createuser = paramMap.get("createuser");
                String status = paramMap.get("status");
                DynamicObject row = null;//要生成的单据类型
                QFilter qf=new QFilter("nwg5_applicationoid",QCP.equals,applicationOID);
                if (userNumber.equals(createuser)) {
                    DynamicObject wtamBusitripselfbill = BusinessDataServiceHelper.loadSingle("wtam_busitripselfbill", "id,billstatus,treatmethodgroup,nwg5_applicationoid", qf.toArray());
                    DynamicObject busitripselfbill = updateBusitripse(status, wtamBusitripselfbill, "wtam_busitripselfbill");
                    if(busitripselfbill==null){
                        continue;
                    }else{
                        row=busitripselfbill;
                        row.set("applytyperadio",'0');
                    }
                } else {
                    DynamicObject wtam_busitripbill = BusinessDataServiceHelper.loadSingle("wtam_busitripbill", "id,billstatus,treatmethodgroup,nwg5_applicationoid", qf.toArray());
                    DynamicObject busitripbill = updateBusitripse(status, wtam_busitripbill, "wtam_busitripbill");
                    if(busitripbill==null){
                        continue;
                    }else{
                        row=busitripbill;
                        row.set("applytyperadio",'1');
                    }
                }

                logger.info("人员工号=======userNumber{}",userNumber);
                logger.info("查生成人员中的数据=======row{}",row);
                String billno = row.getString("billno");

                if(billno==null || "".equals(billno)) {
                    String number = BosUtil.getNumber(row);
                    row.set("billno", number);
                }

                QFilter userQF = new QFilter("number", QCP.equals, createuser);
                DynamicObject bosUser = BusinessDataServiceHelper.loadSingleFromCache("bos_user", "id,name,number", userQF.toArray());
                if(bosUser == null){
                    bosUser=BusinessDataServiceHelper.loadSingleFromCache("bos_user", "id,name,number",new QFilter("number", QCP.equals,"43007523").toArray());
                }


                row.set("org", wtpAttfilebase.get("org"));
                row.set("nwg5_applicationoid",applicationOID);

                DynamicObjectCollection busitriptypes = row.getDynamicObjectCollection("busitriptypes");
                DynamicObject dyType=new DynamicObject(busitriptypes.getDynamicObjectType());
                dyType.set("fbasedataId", tripType);
                busitriptypes.add(dyType);

                row.set("busitriptypes",busitriptypes);
                //考勤档案
                row.set("attfile", wtpAttfilebase);
                //出差人员
                row.set("attfilebasef7", wtpAttfilebase);
                //人员
                row.set("personid", wtpAttfilebase.get("attperson"));
                //创建人
                row.set("creator", bosUser);
                //创建时间
                row.set("createtime", new Date());
                row.set("billstatus", "C");

                Long attId = Long.parseLong(wtpAttfilebase.get("attperson.id").toString());
                Date startTime;
                Date endTime;
                try {
                    String start= paramMap.get("startTime");
                    String str = DateUtil.getISO8601Timestamp(start);
                    startTime = sdf.parse(str);//客开出差单开始时间
                    String ends = paramMap.get("endTime");
                    String end = DateUtil.getISO8601Timestamp(ends);
                    endTime = sdf.parse(end);//客开出差单结束时间
                } catch (Exception e) {
                    return null;
                }
                paramMap.put("userID",attId.toString());
                paramMap.put("tripType",tripType.getPkValue().toString());
                Map<String, Object> objectMap = instance.getSceneNumber(attId, startTime, endTime);
                DynamicObjectCollection collection = row.getDynamicObjectCollection("entryentity");
                collection.clear();
                instance.addBusitripselfEntry(paramMap, objectMap, collection);
                if (collection.size() == 0) {
                    logger.info("分录为生成数据");
                continue;
                }
                logger.info("分录数据{}", collection);

                instance.minDateTime(collection, row);
                logger.info("保存对象.row{}", row);
                Object[] save = save(new DynamicObject[]{row});
                logger.info("保存对象.save{}", save);
            }catch (Exception e){
             logger.error("getEvectionBill.e{}",e);
            }
        }

        return "生成成功";
    }


    private DynamicObject updateBusitripse(String status,DynamicObject dynamic,String entityName){
        logger.info("updateBusitripse====status{}；====entityName{}",status,entityName);
        if(dynamic == null && status.equals("1003")){
            dynamic = BusinessDataServiceHelper.newDynamicObject(entityName);//出差申请单
            return dynamic;
        }else
            if(dynamic != null && (status.equals("1011") || status.equals("1009") || status.equals("1012"))){
                dynamic.set("billstatus", 'F');
                update(dynamic);
                return null;
        }else
            if (dynamic != null && status.equals("1003")) {
                DynamicObject single = BusinessDataServiceHelper.loadSingleFromCache(dynamic.getPkValue(), dynamic.getDynamicObjectType().getName());
                return single;
            }
        return null;
    }
}
